/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"fmt"
	"os"

	"gitee.com/InsignificantDust/msrv/config"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "msrv",
	Short: "Manage your service",
	Long: `A tool manage services. It can create a system service, you can deploy,
update, rollback, uninstall the service accroding your config.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	// Run: func(cmd *cobra.Command, args []string) { },
}

var conf string
var msrvConfig config.Config

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.

	// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.msrv.yaml)")

	// Cobra also supports local flags, which will only run
	// when this action is called directly.

	cobra.OnInitialize(initConfig)
	rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	rootCmd.PersistentFlags().StringVarP(&conf, "conf", "c", "", "The config file of the services (Default: /etc/msrv.yaml)")
}

func initConfig() {
	viper.SetConfigName("msrv")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(confPath())
	viper.AutomaticEnv()
	viper.SetEnvPrefix("MSRV")
	if err := viper.ReadInConfig(); err != nil {
		fmt.Println("Using config File:", viper.ConfigFileUsed())
	}
	if err := viper.Unmarshal(&msrvConfig); err != nil {
		fmt.Printf("%v\n", err)
	}
}

func confPath() string {
	default_config := "/etc"
	if conf != "" {
		return conf
	}
	confdir := os.Getenv("MSRV_CONFIG")
	if confdir == "" {
		return default_config
	}
	return confdir
}
